var express = require('express');
var router = express.Router();

var MongoClient=require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/mui';


router.all('*', function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");  
    res.header("Access-Control-Allow-Headers", "X-Requested-With");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    res.header("X-Powered-By",' 3.2.1')  
    res.header("Content-Type", "application/json;charset=utf-8");  
    next();  
});  


// 登录按钮的接口
router.get('/', function(req, res, next) {
	var user_name=req.query.username;
	var user_pwd=req.query.userpwd;
	var result={
		code:0,
		message:'登录成功！'
	}
	var data = {
		username:user_name,
		password:user_pwd
	}
	MongoClient.connect(DB_CONN_STR, function(err,db) {
		if (err) {
	 		console.log(err);
	 		result.message='连接数据库失败！'
	 		result.code=-2;
		} else {
			var coll = db.collection('users');
			coll.find(data).count(function(err,num){
				console.log()
				if(err){
					console.log(err);
					result.message='账号或密码错误！';
					result.code=-1;					
					res.send(result);
				}else{
					if (num>0) {
						res.send(result);	
					} else {
						result.message='账号或密码错误！';
						result.code=-1;					
						res.send(result);
					}
				}
				db.close();
			});
		}
		
	})   

});


module.exports = router;
